package org.example.demos.pattern.singleton;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DatabaseConnectionPool {
    private static DatabaseConnectionPool instance;
    private List<Connection> connectionPool;
    private String dbUrl;
    private String dbUser;
    private String dbPassword;
    private DatabaseConnectionPool() {
        connectionPool = new ArrayList<>();
        dbUrl = "jdbc:mysql://localhost:3306/mydatabase”; dbUser = “root”";
        dbPassword = "password";
        init();
    }

    public static synchronized DatabaseConnectionPool getInstance() {
        if (instance == null) {
            instance = new DatabaseConnectionPool();
        }
        return instance;
    }

    public synchronized Connection getConnection() throws SQLException {
        if (connectionPool.isEmpty()) {
            Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            connectionPool.add(conn);
            return conn;
        } else {
            return connectionPool.remove(0);
        }
    }
    private void init() {
        for (int i = 0; i < 10; i++) {
            try {
                connectionPool.add(DriverManager.getConnection(dbUrl, dbUser, dbPassword));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}